<template>
	<view class="content">
		<uv-sticky >
			<view class="fixed_head_box">
				<navBar @height="barHeight=$event" :store="storeData" :padding="padding" ref="uniIndexedList"></navBar>
			</view>
		</uv-sticky>
		
		<view class="swiper">
			<uv-swiper
				:list="swiperList"
				keyName="activityImgUrl"
				indicator
				indicatorMode="line"
				circular
				height="200"
				radius="10"
				@click="btnSwiper"
			></uv-swiper>
		</view>
		<view class="category">
			<view>
				<uv-grid :border="false" col="4" customStyle="margin-top: 20rpx;">
					<uv-grid-item v-for="(item,index) in myCategorList" @click="goBusinessld(item)" customStyle="margin-bottom: 20rpx;"
						:key="index">
						<image class="grid-img" :src="item.icon" mode="aspectFill"></image>
						<text class="grid-text2">{{item.name}}</text>
					</uv-grid-item>
				</uv-grid>
			</view>
		</view>
		
		<view class="cart-content">
			<view class="title">
				<view class="title-left">热销产品</view>
			</view>
			<view class="recommend-box">
				<view class="goods-block" v-for="(item, index) in goodsList" :key="index" :data-index="index">
					<view class="goods-box">
						<image class="goods-img" :src="item.rotationImgsJson[0]" mode="" @click.native="navToDetailPage(item)"></image>
						<view class="goods-name" @click.native="navToDetailPage(item)">{{ item.goodsName }}</view>
						<view class="goods-price">
							<view class="price" @click.native="navToDetailPage(item)">
								<view class="price-left">
									<text>￥</text>
									<text class="price-text">{{ item.goodsPrice }}</text>
								</view>
								<view class="price-right" v-if="item.scribePrice > 0">
									<text>￥</text>
									<text>{{ item.scribePrice }}</text>
								</view>
							</view>
							<uv-icon name="shopping-cart" color="#ff4544" size="28" @click="addToCart(item)"></uv-icon>
						</view>
						<view class="month_sales"></view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { getBusinessInfoList, getRecommen, getHomeDataInfo, getCategory, insertPlugsShopCart, userIsLogin,searchPlugsGoodsSpecificationByGoodsId,searchHotGoodsList } from '../../utils/api.js';
import { authorizedLocation } from '../../utils/api.js';
import QQMapWX from '../../utils/qqmap-wx-jssdk.min.js';
export default {
	data() {
		return {
			list: [],
			scrollHeight: 0,
			swiperList: [],
			BusinessInfoList: [],
			categorList: [],
			goodsList: [],
			mapInfo: {},
			nowBusinessInfo: {},
			storeData:'',
			myCategorList:[
				{
					icon:'https://oss.daccf.com/chjii12wgts2zgguh25rd/全部/b01bf1ba-9277-444e-a9f3-3766b42f5f45.png',
					name:'我的门店',
					pages:'/pages/index/busList?id=1'
				},
				{
					icon:'https://oss.daccf.com/chjii12wgts2zgguh25rd/全部/11cf39e1-448e-4f9d-b002-a6f1792112ab.png',
					name:'领养活动',
					pages:'/pages/index/lingyang/lingyang'
					
				},
				{
					icon:'https://oss.daccf.com/chjii12wgts2zgguh25rd/全部/c95f96d0-ee5d-490c-9f2e-53b196e0c8b8.png',
					name:'养宠知识',
					pages:'/pages/index/noticeList/noticeList'
				},
				{
					icon:'https://oss.daccf.com/chjii12wgts2zgguh25rd/全部/1e8e303e-42b0-4eaa-97b0-02b20e0339c5.png',
					name:'商家加盟',
					pages:'/pages/index/jiameng/jiameng'
					
				},
				{
					icon:'https://oss.daccf.com/chjii12wgts2zgguh25rd/全部/3c05b984-d1ff-407e-892e-8955e1ff2451.png',
					name:'履约记录',
					pages:'/pages/index/performance/performance'
					
				}
			]
		};
	},
	
	onLoad() {
		// this.getmap();
	},
	onShow() {
		if (!uni.getStorageSync('nowBusinessInfo')) {
			this.getmap();
		} else {
			this.nowBusinessInfo = uni.getStorageSync('nowBusinessInfo');
			this.storeData = this.nowBusinessInfo.jsonViewData.businessName;
			this.getswiperList();
			this.getCategoryList();
			this.getHomeDataInfo();
		}
	},
	methods: {
		showPopup() {
			this.$refs.popup.open();
		},
		close() {
			this.$refs.popup.close();
		},
		// 获取定位信息
		getmap() {
			console.log(123);
			// 我的项目是使用uniapp编写，获取经纬度使用uni.getLocation()； 微信原生使用wx.getLocation();
			uni.getLocation({
				type: 'wgs84',
				success: res => {
					let qqmapsdk = new QQMapWX({
						key: 'GJGBZ-P5MK3-BRB3O-ORGYN-ZW7SE-ISFOI'
					});
					qqmapsdk.reverseGeocoder({
						location: {
							latitude: res.latitude,
							longitude: res.longitude
						},
						success: re => {
							uni.setStorage({
								key: 'mapInfo',
								data: re.result
							});
							this.mapInfo = re.result;
							this.loadData();
						}
					});
				},
				 fail (error) {
				                //点击了拒绝授权后--就一直会进入失败回调函数--此时就可以在这里重新拉起授权窗口
				                console.log('拒绝授权', error)
				
				                uni.showModal({
				                  title: '提示',
				                  content: '若点击不授权，将无法使用位置功能',
				                  cancelText: '不授权',
				                  cancelColor: '#999',
				                  confirmText: '授权',
				                  confirmColor: '#f94218',
				                  success (res) {
				                    console.log(res)
				                    if (res.confirm) {
				                      // 选择弹框内授权
				                      uni.openSetting({
				                        success (res) {
				                          console.log(res.authSetting)
				                        }
				                      })
				                    } else if (res.cancel) {
				                      // 选择弹框内 不授权
				                      console.log('用户点击不授权')
				                    }
				                  }
				                })
				}
				
			});
		},
		// 获取当前店铺信息
		loadData() {
			let data = {
				latitude: '0',
				longitude: 0
			};
			getBusinessInfoList(data).then(res => {
				if (res.code == 200) {
					this.BusinessInfoList = res.body;
					this.BusinessInfoList.forEach(item => {
						item.distance = this.space(
							item.jsonViewData.businessAddress.latitude,
							item.jsonViewData.businessAddress.longitude,
							this.mapInfo.location.lat,
							this.mapInfo.location.lng
						);
					});

					let aa = Math.min.apply(
						Math,
						this.BusinessInfoList.map(item => {
							return item.distance;
						})
					);
					this.nowBusinessInfo = this.BusinessInfoList.find(item => aa === item.distance);
					this.storeData = this.nowBusinessInfo.jsonViewData.businessName;
					uni.setStorage({
						key: 'nowBusinessInfo',
						data: this.nowBusinessInfo
					});

					this.getswiperList();
					this.getCategoryList();
					this.getHomeDataInfo();
				}
			});
		},
		// 计算两点之间的经纬度
		space(lat1, lng1, lat2, lng2) {
			console.log(lat1, lng1, lat2, lng2);
			var radLat1 = (lat1 * Math.PI) / 180.0;
			var radLat2 = (lat2 * Math.PI) / 180.0;
			var a = radLat1 - radLat2;
			var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
			var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
			s = s * 6378.137;
			s = Math.round(s * 10000) / 10000;
			return s; // 单位千米
		},
		// 获取轮播
		getswiperList() {
			let data = {
				businessId: this.nowBusinessInfo.jsonViewData.businessId.toString()
			};
			getRecommen(data).then(res => {
				if (res.code == 200) {
					// this.carouselList = res.body
					let arr1 = [];
					let arr2 = [];
					let arr3 = [];
					arr1 = res.body.filter(itm => itm.type === 'home_data');
					arr2 = res.body.filter(itm => itm.type === 'homeTwo');
					arr3 = res.body.filter(itm => itm.type === 'homeThree');
					this.swiperList = [...arr1, ...arr2, ...arr3];
					console.log(this.swiperList, 777);
				}
			});
		},
		// 获取分类数据
		getCategoryList() {
			let data = {
				businessId: this.nowBusinessInfo.jsonViewData.businessId.toString(),
				pid:0
			};
			getCategory(data).then(res => {
				if (res.code == 200) {
					this.categorList = [];
					for (let i = 0; i < res.body.list.length; i++) {
						if (i > 4) {
							break;
						} else {
							this.categorList.push(res.body.list[i]);
						}
					}
				}
			});
		},
		// 获取热门数据
		// getHomeDataInfo() {
		// 	let data = {
		// 		businessId: this.nowBusinessInfo.jsonViewData.businessId.toString()
		// 	};
		// 	getHomeDataInfo(data).then(res => {
		// 		if (res.code == 200) {
		// 			this.goodsList = res.body.jsonViewData[0].data;
		// 			this.goodsList.forEach(item => {
		// 				if(item.ext_json){
		// 					item.ext_json = JSON.parse(item.ext_json);
		// 				}
		// 			});
		// 		}
		// 	});
		// },
		
		// 获取热门数据
		getHomeDataInfo() {
			let data = {
				businessId: this.nowBusinessInfo.jsonViewData.businessId.toString(),
				recommendationStatus:1,
				size:100
			};
		
			searchHotGoodsList(data).then(res => {
				if (res.code == 200) {
					res.body.list.forEach((item)=>{
						if(item.rotationImgsJson){
							item.rotationImgsJson=JSON.parse(item.rotationImgsJson)
						}
					})
					this.goodsList = res.body.list;
				}
			});
		},
		
		

		// 去店铺列表
		goBusinessld(item) {
			if(item.pages){
				uni.navigateTo({
					url: item.pages
				});
			}else{
				uni.showToast({
					icon:'none',
					title:'暂未开通'
				})
			}
			
		},
		goPath(id) {
			uni.navigateTo({
				url: `/pages/shopDetails/shopDetails?id=${id}`
			});
		},
		
		goGua() {
			uni.navigateTo({
				url: '/pages/guarantee/guarantee'
			});
		},
		btnSwiper(index) {
			console.log(this.swiperList[index]);
			if (this.swiperList[index].type == 'home_data') {
				uni.navigateTo({
					url: '/pages/index/gzhWenzhang/gzhWenzhang?url=' + this.swiperList[index].detailsImgAndPageUrl
				});
			} else if (this.swiperList[index].type == 'homeTwo') {
				uni.navigateTo({
					url: `/pages/shopDetails/shopDetails?id=${this.swiperList[index].detailsImgAndPageUrl}`
				});
			} else if (this.swiperList[index].type == 'homeThree') {
				wx.navigateToMiniProgram({
					appId: this.swiperList[index].detailsImgAndPageUrl,
					path: '/pages/index/index',
					//develop开发版；trial体验版；release正式版
					envVersion: 'release',
					success(res) {
						// 打开成功
						console.log('跳转小程序成功！', res);
					}
				});
			}
		},

		goXCX() {
			wx.navigateToMiniProgram({
				appId: 'wx8a87d5a8d90b4df2',
				path: '/pages/index/index',
				//develop开发版；trial体验版；release正式版
				envVersion: 'release',
				success(res) {
					// 打开成功
					console.log('跳转小程序成功！', res);
				}
			});
		},
		goSearch(){
			uni.navigateTo({
				url: '/pages/index/search/search'
			});
		},
		navToDetailPage(item) {
			//测试数据没有写id，用title代替
			let id = item.id;
			uni.navigateTo({
				url: `/pages/porduct/porduct?id=${id}`
			});
		},
		categoryItemTap(item){
			let id = item.id;
			uni.navigateTo({
				url: `/pages/porduct/list?id=${id}&name=${item.categoryName}`
			});
		},
		
		addToCart(item) {
			let token = uni.getStorageSync('userInfo').accessToken;
		
			if (token == null) {
				uni.showModal({
					title: '提示',
					content: '登录才能添加宝贝哦~',
					success: function(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/user/login'
							});
						} else if (res.cancel) {
						}
					}
				});
			} else {
				searchPlugsGoodsSpecificationByGoodsId( {
					goodsId: item.id
				}).then(res => {
					if (res.code == 200) {
						if (res.body.plugsGoodsSpecificationList.length == 0) {
							let postData = {
								businessId: this.nowBusinessInfo.businessId.toString(),
								goodsId: item.id,
								goodsCategoryId: item.categoryId,
								goodsNum: 1,
								goodsSpecificationIds: '0'
							};
							if (item.stockNum <= 0) {
								uni.showModal({
									title: '提示',
									content: '库存不足!',
									showCancel: false
								});
								return
							}
							item.stockNum--
							insertPlugsShopCart(postData).then(res => {
								if (res.code == 200) {
									uni.showToast({
										title: '加入成功',
										icon: 'none'
									});
								}else{
									item.stockNum++
								}
							});
						} else {
							let postData = {
								businessId: this.nowBusinessInfo.businessId.toString(),
								goodsId: item.id,
								goodsCategoryId: item.categoryId,
								goodsNum: 1,
								goodsSpecificationIds: res.body.plugsGoodsSpecificationList[0].id
							};
							if (res.body.plugsGoodsSpecificationList[0].stockNum <= 0) {
								uni.showModal({
									title: '提示',
									content: '库存不足!',
									showCancel: false
								});
								return
							}
							res.body.plugsGoodsSpecificationList[0].stockNum--
							insertPlugsShopCart(postData).then(res => {
								if (res.code == 200) {
									uni.showToast({
										title: '加入成功',
										icon: 'none'
									});
								}else{
									res.body.plugsGoodsSpecificationList[0].stockNum++
								}
							});
						}
					}
				});
			}
		}
		
	}
};
</script>

<style lang="scss">
page {
	padding: 0;
	box-sizing: border-box;
}

.content {
	.fixed_head_box {
	background-color: #fff;
	}
	.swiper{
		padding: 0 20rpx;
	}
		.category {
			padding: 20rpx 0;
			box-sizing: border-box;
			margin-top: -80rpx;
			z-index: 99;
			width: 96%;
			margin: 0rpx auto;
	
			.grid-img {
				width: 100rpx;
				height: 100rpx;
				border-radius: 16rpx;
			}
	
			.grid-text2 {
				margin-top: 12rpx;
				font-size: 26rpx;
			}
		}
		
		.cart-content {
			margin-top: 25rpx;
			padding: 20rpx;
			background-color: #fff;
			border-radius: 20rpx;

			.title {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 80rpx;

				.title-left {
					font-size: 36rpx;
					font-weight: 700;
				}

				.title-right {
					display: flex;
					align-items: center;
					font-size: 30rpx;
					font-weight: 700;
				}
			}
			.recommend-box {
				width: 100%;
				display: flex;
				justify-content: space-between;
				flex-wrap: wrap;
			
				.goods-block {
					width: 48%;
				}
				.goods-box {
					width: 100%;
					height: 470rpx;
					border-radius: 16rpx;
					box-sizing: border-box;
					background-color: #fff;
					margin-bottom: 20rpx;
					border: 3rpx solid #f5f5f5;
					.goods-img {
						width: 100%;
						height: 330rpx;
						border-radius: 16rpx 16rpx 0 0;
					}
					.goods-name {
						width: 94%;
						margin: 10rpx auto;
						font-size: 28rpx;
						display: -webkit-box; //将对象作为弹性伸缩盒子模型显示
						-webkit-box-orient: vertical; //设置或检索伸缩盒对象的子元素的排列方式
						-webkit-line-clamp: 1; //一个块元素显示的文本的行数
						overflow: hidden; //溢出隐藏
					}
					.goods-price {
						width: 94%;
						margin: auto;
						display: flex;
						align-items: center;
						justify-content: space-between;
						.price {
							color: #ff4544;
							display: flex;
							align-items: center;
			
							.price-text {
								font-size: 34rpx;
								font-weight: 600;
							}
			
							.price-right {
								margin-left: 12rpx;
								font-size: 26rpx !important;
								font-weight: 400 !important;
								color: #aaa;
								margin-left: 18rpx;
								text-decoration: line-through;
							}
						}
					}
			
					.month_sales {
						width: 94%;
						margin: auto;
						font-size: 22rpx;
						color: #aaa;
					}
				}
			}
		}
}
</style>
